import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import jwt from 'jwt-decode'
import {otherRouter, appRouters} from '../router/routers'
import md5 from 'js-md5'


Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    menuList: [...appRouters],
    routers: [otherRouter, ...appRouters],
    menulist: [],
    currentPath: [],
    openNames: [],
    userid: null,
    expire: '',
    username: '',
    token: '',
    timestamp: parseInt(new Date().getTime() / 1000),
    headers: {}
  },
  getters: {},
  // computed: {
  //   headers() {
  //     return {"signature":md5(this.timestamp+"ba8a917e-c67a-11ea-9d94-acde48001122"), "timestamp":this.timestamp, "appname":"bybit", "username":this.username}
  //   }
  // },
  mutations: {
    updateToken: (state, token) => {
      state.token = token
      localStorage.token = token
    },
    decodeToken: (state, token) => {
      state.userid = jwt(localStorage.token).user_id
      state.expire = new Date(1000 * jwt(localStorage.token).exp)
      state.username = jwt(localStorage.token).username
    },
    setOpenNames: (state, name) => {
      state.openNames = [name]
    },
    setCurrentPath: (state, pathArr) => {
      state.currentPath = pathArr
    },
    removeStorage: state => {
      localStorage.removeItem('token')
    },
    get_headers: (state, data) => {
      state.headers = data
    }

  },
  actions: {
    change_headers: (context, data) => {
      const time = parseInt(new Date().getTime() / 1000)
      context.commit('get_headers', {
        "signature": md5(time + "ba8a917e-c67a-11ea-9d94-acde48001122"),
        "timestamp": time,
        "appname": "bybit",
        "username": context.state.username
      })
    },
    login: async (context, data) => {
      await context.dispatch('change_headers')
      // console.log(context)
      return new Promise((resolve, reject) => {
        axios.post('api/v1.0/accounts/obtain_token/', data).then(resp => {
          context.commit('updateToken', resp.data.token)
          context.commit('decodeToken', resp.data.token)
          resolve(resp)
        }).catch(error => {
          reject(error)
        })
      })
    },
    logout: context => {
      context.commit('removeStorage')
    },
    api_workflows: async (context) => {
      await context.dispatch('change_headers');
      return new Promise((resolve, reject) => {
        // console.log("123", context.state.headers)
        axios.get('/api/v1.0/workflows', {"headers": context.state.headers}).then(resp => {
          // console.log("回复", resp)
          resolve(resp)
        }).catch(error => {
          // console.log("错了")
          reject(error)
        })
      })

      // api_workflows: context => {
      //   context.dispatch('change_headers').then(() => {
      //
      //     return new Promise((resolve, reject) => {
      //       console.log("123", context.state.headers)
      //       axios.get('/api/v1.0/workflows', {"headers": context.state.headers}).then(resp => {
      //         console.log("回复", resp)
      //         resolve(resp)
      //       }).catch(error => {
      //         console.log("错了")
      //         reject(error)
      //       })
      //     })
      //   })

    },
    api_init_state: async (context, params) => {
      await context.dispatch('change_headers')
      return new Promise((resolve, reject) => {
        axios.get(`/api/v1.0/workflows/${params.id}/init_state?username=${context.state.username}`, {"headers": context.state.headers}).then(resp => {
          // axios.get(`/api/v1/service/init_state/${params.id}/`,).then(resp => {
          resolve(resp)
        }).catch(error => {
          reject(error)
        })
      })
    },
    api_post_ticket: async (context, data) => {
      await context.dispatch('change_headers')
      return new Promise((resolve, reject) => {
        axios.post('/api/v1.0/tickets', data,{"headers": context.state.headers}).then(resp => {
          resolve(resp)
        }).catch(error => {
          reject(error)
        })
      })
    },
    api_get_ticket_list: async (context, params) => {
      await context.dispatch('change_headers');
      var url = ''
      let keys = Object.keys(params)
      var query = []
      if (keys.length > 0) {
        for (let i = 0; i < keys.length; i++) {
          query.push(`${keys[i]}=${params[keys[i]]}`)
        }
        url = `/api/v1.0/tickets?${query.join('&')}`
      } else {
        url = '/api/v1.0/tickets'
      }
      // console.log(url)
      return new Promise((resolve, reject) => {
        axios.get(url,{"headers": context.state.headers}).then(resp => {
          resolve(resp)
        }).catch(error => {
          reject(error)
        })
      })
    },
    api_get_ticket_detail: async (context, params) => {
      let url = `/api/v1.0/tickets/${params.id}`
      return new Promise((resolve, reject) => {
        axios.get(url,{"headers": context.state.headers}).then(resp => {
          resolve(resp)
        }).catch(error => {
          reject(error)
        })
      })
    },
    api_get_ticket_step_list: async (context, params) => {
      await context.dispatch('change_headers');
      return new Promise((resolve, reject) => {
        // /api/v1.0/tickets/{}/flowsteps?username={}
        axios.get(`/api/v1.0/tickets/${params.id}/flowsteps?username=${context.state.username}`,{"headers": context.state.headers}).then(resp => {
          resolve(resp)
        }).catch(error => {
          reject(error)
        })
      })
    },
    api_get_ticket_transiton_list: async (context, params) => {
      await context.dispatch('change_headers');
      // console.log(context)
      return new Promise((resolve, reject) => {
        // /api/v1.0/tickets/{}/flowlogs?username={}
        axios.get(`/api/v1.0/tickets/${params.id}/flowlogs?username=${context.state.username}`,{"headers": context.state.headers}).then(resp => {
          resolve(resp)
        }).catch(error => {
          reject(error)
        })
      })
    },
    api_get_ticket_transitions: async (context, params) => {
      await context.dispatch('change_headers');
      // console.log(context)
      return new Promise((resolve, reject) => {
        // /api/v1.0/tickets/{}/transitions?username={}
        axios.get(`/api/v1.0/tickets/${params.id}/transitions?username=${context.state.username}`,{"headers": context.state.headers}).then(resp => {
          resolve(resp)
        }).catch(error => {
          reject(error)
        })
      })
    },
    api_handle_ticket_action: async (context, data) => {
      await context.dispatch('change_headers');
      let url = `/api/v1.0/tickets/${data.id}`
      return new Promise((resolve, reject) => {
        axios.patch(url, data.data,{"headers": context.state.headers}).then(resp => {
          resolve(resp)
        }).catch(error => {
          reject(error)
        })
      })

    },
    api_fetch_account_list: async (context) => {
      await context.dispatch('change_headers');
      return new Promise((resolve, reject) => {
        axios.get('/api/v1.0/accounts/users',{"headers": context.state.headers}).then(resp => {
          resolve(resp)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
})

export default store

// import Vue from 'vue'
// import Vuex from 'vuex'
// import axios from 'axios'
// import jwt from 'jwt-decode'
// import {otherRouter, appRouters} from '../router/routers'
//
// Vue.use(Vuex)
//
// const store = new Vuex.Store({
//   state: {
//     menuList: [...appRouters],
//     routers: [otherRouter, ...appRouters],
//     menulist: [],
//     currentPath: [],
//     openNames: [],
//     userid: null,
//     expire: '',
//     username: '',
//     token: '',
//   },
//   getters: {},
//   mutations: {
//     updateToken: (state, token) => {
//       state.token = token
//       localStorage.token = token
//     },
//     decodeToken: (state, token) => {
//       state.userid = jwt(localStorage.token).user_id
//       state.expire = new Date(1000 * jwt(localStorage.token).exp)
//       state.username = jwt(localStorage.token).username
//     },
//     setOpenNames: (state, name) => {
//       state.openNames = [name]
//     },
//     setCurrentPath: (state, pathArr) => {
//       state.currentPath = pathArr
//     },
//     removeStorage: state => {
//       localStorage.removeItem('token')
//     }
//   },
//   actions: {
//     login: (context, data) => {
//       return new Promise((resolve, reject) => {
//         axios.post('api/v1.0/accounts/obtain_token/', data).then(resp => {
//           context.commit('updateToken', resp.data.token)
//           context.commit('decodeToken', resp.data.token)
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     logout: context => {
//       context.commit('removeStorage')
//     },
//     api_workflows: context => {
//       return new Promise((resolve, reject) => {
//         axios.get('/api/v1.0/workflows').then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_init_state: (context, params) => {
//       return new Promise((resolve, reject) => {
//         axios.get(`/api/v1/service/init_state/${params.id}/`).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_post_ticket: (context, data) => {
//       return new Promise((resolve, reject) => {
//         axios.post('/api/v1/service/create_ticket/', data).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_get_ticket_list: (context, params) => {
//       var url = ''
//       let keys = Object.keys(params)
//       var query = []
//       if (keys.length > 0) {
//         for (let i = 0; i < keys.length; i++) {
//           query.push(`${keys[i]}=${params[keys[i]]}`)
//         }
//         url = `/api/v1/service/tickets/?${query.join('&')}`
//       } else {
//         url = '/api/v1/service/tickets/'
//       }
//       console.log(url)
//       return new Promise((resolve, reject) => {
//         axios.get(url).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_get_ticket_detail: (context, params) => {
//       let url = `/api/v1/service/tickets/${params.id}/`
//       return new Promise((resolve, reject) => {
//         axios.get(url).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_get_ticket_step_list: (context, params) => {
//       return new Promise((resolve, reject) => {
//         axios.get(`/api/v1/service/steps/${params.id}/`).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_get_ticket_transiton_list: (context, params) => {
//       return new Promise((resolve, reject) => {
//         axios.get(`/api/v1/service/logs/${params.id}/`).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_get_ticket_transitions: (context, params) => {
//       return new Promise((resolve, reject) => {
//         axios.get(`/api/v1/service/actions/${params.id}/`).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_handle_ticket_action: (context, data) => {
//       let url = `/api/v1/service/tickets/${data.id}/`
//       return new Promise((resolve, reject) => {
//         axios.patch(url, data.data).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//
//     },
//     api_fetch_account_list: context => {
//       return new Promise((resolve, reject) => {
//         axios.get('/api/v1/account/users/fetch-users/').then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     }
//   }
// })
//
// export default store

// import Vue from 'vue'
// import Vuex from 'vuex'
// import axios from 'axios'
// import jwt from 'jwt-decode'
// import { otherRouter, appRouters } from '../router/routers'
//
// Vue.use(Vuex)
//
// const store = new Vuex.Store({
//   state: {
//     menuList: [...appRouters],
//     routers: [otherRouter, ...appRouters],
//     menulist: [],
//     currentPath: [],
//     openNames: [],
//     userid: null,
//     expire: '',
//     username: '',
//     token: ''
//   },
//   getters: {},
//   mutations: {
//     updateToken: (state, token) => {
//       state.token = token
//       localStorage.token = token
//     },
//     decodeToken: (state, token) => {
//       state.userid = jwt(localStorage.token).user_id
//       state.expire = new Date(1000 * jwt(localStorage.token).exp)
//       state.username = jwt(localStorage.token).username
//     },
//     setOpenNames: (state, name) => {
//       state.openNames = [name]
//     },
//     setCurrentPath: (state, pathArr) => {
//       state.currentPath = pathArr
//     },
//     removeStorage: state => {
//       localStorage.removeItem('token')
//     }
//   },
//   actions: {
//     login: (context, data) => {
//       return new Promise((resolve, reject) => {
//         axios.post('/api/v1/account/obtain_token/', data).then(resp => {
//           context.commit('updateToken', resp.data.token)
//           context.commit('decodeToken', resp.data.token)
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     logout: context => {
//       context.commit('removeStorage')
//     },
//     api_workflows: context => {
//       return new Promise((resolve, reject) => {
//         axios.get('/api/v1/service/workflows/').then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_init_state: (context, params) => {
//       return new Promise((resolve, reject) => {
//         axios.get(`/api/v1/service/init_state/${params.id}/`).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_post_ticket: (context, data) => {
//       return new Promise((resolve, reject) => {
//         axios.post('/api/v1/service/create_ticket/', data).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_get_ticket_list: (context, params) => {
//       var url = ''
//       let keys = Object.keys(params)
//       var query = []
//       if (keys.length > 0) {
//         for (let i = 0; i < keys.length; i++) {
//           query.push(`${keys[i]}=${params[keys[i]]}`)
//         }
//         url = `/api/v1/service/tickets/?${query.join('&')}`
//       } else {
//         url = '/api/v1/service/tickets/'
//       }
//       console.log(url)
//       return new Promise((resolve, reject) => {
//         axios.get(url).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_get_ticket_detail: (context, params) => {
//       let url = `/api/v1/service/tickets/${params.id}/`
//       return new Promise((resolve, reject) => {
//         axios.get(url).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_get_ticket_step_list: (context, params) => {
//       return new Promise((resolve, reject) => {
//         axios.get(`/api/v1/service/steps/${params.id}/`).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_get_ticket_transiton_list: (context, params) => {
//       return new Promise((resolve, reject) => {
//         axios.get(`/api/v1/service/logs/${params.id}/`).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_get_ticket_transitions: (context, params) => {
//       return new Promise((resolve, reject) => {
//         axios.get(`/api/v1/service/actions/${params.id}/`).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },
//     api_handle_ticket_action: (context, data) => {
//       let url = `/api/v1/service/tickets/${data.id}/`
//       return new Promise((resolve, reject) => {
//         axios.patch(url, data.data).then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//
//     },
//     api_fetch_account_list: context => {
//       return new Promise((resolve, reject) => {
//         axios.get('/api/v1/account/users/fetch-users/').then(resp => {
//           resolve(resp)
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     }
//   }
// })
//
// export default store
